package com.canal.collection.controller;

import com.canal.collection.constains.DeviceEnum;
import com.canal.collection.exception.BuzException;
import com.canal.collection.result.Result;
import com.canal.collection.result.ResultUtil;
import com.canal.collection.service.DataCollectionService;
import com.canal.collection.transfer.req.RegReq;
import com.canal.collection.transfer.req.VisitReq;
import com.canal.collection.util.IpUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;

/**
 * @author yangbo
 * @date 2020-07-02 14:07
 */
@RestController
public class PvUvController {

    @Autowired
    private DataCollectionService dataCollectionService;

    /**
     * pv uv访问采集接口
     * @param visitReq
     * @param bindingResult
     * @param request
     * @return
     * @throws BuzException
     */
    @PostMapping(value = "/gateway/put")
    public Result visit(@RequestBody @Validated VisitReq visitReq,
                        BindingResult bindingResult,
                        HttpServletRequest request) throws BuzException {
        if(bindingResult.hasErrors()) {
            throw new BuzException(400,bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        if(StringUtils.isBlank(visitReq.getIp())) {
            visitReq.setIp(IpUtils.getIpAddr(request));
        }
        if(StringUtils.isBlank(visitReq.getDeviceName())) {
            String ua = visitReq.getUa();
            if(ua.contains(DeviceEnum.ANDROID.getDevice())) {
                visitReq.setDeviceName(DeviceEnum.ANDROID.getDevice());
            } else if (ua.contains(DeviceEnum.LINUX.getDevice())) {
                visitReq.setDeviceName(DeviceEnum.LINUX.getDevice());
            } else if (ua.contains(DeviceEnum.IPHONE.getDevice())) {
                    visitReq.setDeviceName(DeviceEnum.IPHONE.getDevice());
            } else if(ua.contains(DeviceEnum.WINDOWS.getDevice())) {
                    visitReq.setDeviceName(DeviceEnum.WINDOWS.getDevice());
            } else {
                visitReq.setDeviceName(DeviceEnum.OTHER.getDevice());
            }
        }
        dataCollectionService.pvUv(visitReq);
        return ResultUtil.makeSuccess("success");
    }

    /**
     * 发送短信
     * @param tele
     * @param code
     * @param request
     * @return
     * @throws BuzException
     */
    @GetMapping(value = "/gateway/send")
    public Result sendSms(@RequestParam(value = "tele") String tele,
                          @RequestParam(value = "code") String code,
                          @RequestHeader(value = "channel") Integer channel,
                          HttpServletRequest request) throws BuzException {
        if(StringUtils.isBlank(code)) {
            return ResultUtil.makeFailure(399,"请输入图形验证码");
        }
        //校验图形验证码
        String yesCode = (String) request.getSession().getAttribute("code");
        if(StringUtils.isBlank(yesCode)) {
            return ResultUtil.makeFailure(400,"图形验证码已过期");
        }
        if(!yesCode.toLowerCase().equals(code.toLowerCase())) {
            return ResultUtil.makeFailure(401,"验证码错误");
        }
        request.getSession().invalidate();
        //校验手机号是否已存在
        if(dataCollectionService.existPhone(tele)) {
            //手机号存在了，就直接返回下载路径
            String apkUrl = dataCollectionService.getApkUrl(channel);
            return ResultUtil.makeFailure(402,apkUrl);
        }
        //校验手机号是否能发送短信
        if(dataCollectionService.canSend(tele)) {
            return ResultUtil.makeFailure(403,"短信发送过于频繁");
        }
        //生成短信验证码
        StringBuilder smsCode = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            smsCode.append(RandomUtils.nextInt(0,9));
        }
        //发送
        dataCollectionService.sendSms(tele,smsCode.toString());
        return ResultUtil.makeSuccess("发送成功");
    }

    /**
     * 发送短信
     * @param tele
     * @param request
     * @return
     * @throws BuzException
     */
    @GetMapping(value = "/gateway/send/v2")
    public Result sendSmsNotCode(@RequestParam(value = "tele") String tele,
                          @RequestHeader(value = "channel") Integer channel,
                          HttpServletRequest request) throws BuzException {
        //校验手机号是否已存在
        if(dataCollectionService.existPhone(tele)) {
            //手机号存在了，就直接返回下载路径
            String apkUrl = dataCollectionService.getApkUrl(channel);
            return ResultUtil.makeFailure(402,apkUrl);
        }
        //校验手机号是否能发送短信
        if(dataCollectionService.canSend(tele)) {
            return ResultUtil.makeFailure(403,"短信发送过于频繁");
        }
        //生成短信验证码
        StringBuilder smsCode = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            smsCode.append(RandomUtils.nextInt(0,9));
        }
        //发送
        dataCollectionService.sendSms(tele,smsCode.toString());
        return ResultUtil.makeSuccess("发送成功");
    }

    /**
     * 注册
     * @param regReq
     * @param bindingResult
     * @return
     * @throws BuzException
     */
    @PostMapping(value = "/gateway/reg")
    public Result<String> register(@RequestBody @Validated RegReq regReq,
                           BindingResult bindingResult,
                           HttpServletRequest request) throws BuzException, UnsupportedEncodingException {
        if(bindingResult.hasErrors()) {
            throw new BuzException(400,bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        if(StringUtils.isBlank(regReq.getIp())) {
            regReq.setIp(IpUtils.getIpAddr(request));
        }
        String apkUrl = dataCollectionService.regUser(regReq);
        return ResultUtil.makeSuccess("success",apkUrl);

    }

    /**
     * 规避错误
     * @return
     */
    @GetMapping(value = "/v1/users/login")
    public Result test() {
        return ResultUtil.makeSuccess("ok");
    }

}
